import SwiftUI
import Charts

struct EnhancedCultivationStatisticsView: View {
    @State private var selectedType: TaskType = .body
    @State private var selectedTimeRange: TimeRange = .month
    
    let cultivationData: EnhancedCultivationData
    
    var body: some View {
        ZStack(alignment: .bottom) {
            ScrollView {
                VStack(spacing: 24) {
                    timeRangeSelector
                    heatmapView
                    lineChartView
                    barChartView
                    radarChartView
                    scatterPlotView
                    gaugeChartView
                }
                .padding()
                .padding(.bottom, 50) // Add padding for the tab bar
            }
            .background(Color(.systemGroupedBackground))
            
            // Custom Tab Bar
            HStack(spacing: 0) {
                ForEach(TaskType.allCases, id: \.self) { type in
                    Button(action: {
                        withAnimation {
                            selectedType = type
                        }
                    }) {
                        VStack(spacing: 4) {
                            Text(type.rawValue)
                                .font(.system(size: 17))
                            
                            // Indicator line
                            Rectangle()
                                .fill(type.color)
                                .frame(height: 2)
                                .opacity(selectedType == type ? 1 : 0)
                        }
                        .frame(maxWidth: .infinity)
                    }
                    .foregroundColor(selectedType == type ? type.color : .secondary)
                }
            }
            .padding(.horizontal)
            .frame(height: 44)
            .background(Color(.systemBackground))
            .overlay(
                Rectangle()
                    .frame(height: 1)
                    .foregroundColor(Color(.separator))
                    .opacity(0.5),
                alignment: .top
            )
        }
        .navigationTitle("修炼统计")
    }
    
    private var timeRangeSelector: some View {
        Picker("Time Range", selection: $selectedTimeRange) {
            ForEach(TimeRange.allCases, id: \.self) { range in
                Text(range.rawValue).tag(range)
            }
        }
        .pickerStyle(SegmentedPickerStyle())
    }
    
    private var heatmapView: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("修炼热力图")
                .font(.headline)
            
            VStack(spacing: 0) {
                HStack(alignment: .top, spacing: 0) {
                    // Weekday labels column
                    VStack(alignment: .trailing, spacing: 0) {
                        ForEach(["一", "二", "三", "四", "五", "六", "日"], id: \.self) { day in
                            Text(day)
                                .font(.system(size: 12))
                                .foregroundColor(.secondary)
                                .frame(height: 24)
                                .frame(width: 20, alignment: .trailing)
                                .padding(.trailing, 8)
                        }
                    }
                    
                    ScrollView(.horizontal, showsIndicators: false) {
                        VStack(spacing: 0) {
                            HStack(spacing: 4) {
                                if let data = cultivationData.heatmapData[selectedTimeRange] {
                                    ForEach(0..<data.count, id: \.self) { weekIndex in
                                        VStack(spacing: 4) {
                                            ForEach(0..<7, id: \.self) { dayIndex in
                                                RoundedRectangle(cornerRadius: 2)
                                                    .fill(selectedType.color.opacity(data[weekIndex][dayIndex]))
                                                    .frame(width: 20, height: 20)
                                            }
                                        }
                                    }
                                }
                            }
                            
                            HStack(spacing: 4) {
                                if selectedTimeRange == .month {
                                    ForEach(0..<5) { weekIndex in
                                        if weekIndex == 0 || weekIndex == 2 || weekIndex == 4 {
                                            Text("\(weekIndex * 7 + 1)日")
                                                .font(.system(size: 12))
                                                .foregroundColor(.secondary)
                                                .frame(width: 60, alignment: .center)
                                        }
                                    }
                                } else {
                                    ForEach(1...12, id: \.self) { month in
                                        if month % 3 == 1 {
                                            Text("\(month)月")
                                                .font(.system(size: 12))
                                                .foregroundColor(.secondary)
                                                .frame(width: 120, alignment: .center)
                                        }
                                    }
                                }
                            }
                            .padding(.top, 4)
                        }
                    }
                }
            }
            .padding(.vertical, 8)
            
            HStack {
                Text("较少")
                    .font(.caption)
                    .foregroundColor(.secondary)
                Spacer()
                HStack(spacing: 2) {
                    ForEach(0..<5) { i in
                        RoundedRectangle(cornerRadius: 2)
                            .fill(selectedType.color.opacity(Double(i) / 4))
                            .frame(width: 20, height: 20)
                    }
                }
                Spacer()
                Text("较多")
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
            .padding(.top, 8)
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(15)
    }
    
    private var lineChartView: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("打卡率趋势")
                .font(.headline)
            
            Chart {
                ForEach(Array(cultivationData.completionRates[selectedType]?[selectedTimeRange]?.enumerated() ?? [].enumerated()), id: \.element) { index, rate in
                    LineMark(
                        x: .value("Period", index),
                        y: .value("Rate", rate)
                    )
                    .foregroundStyle(selectedType.color.gradient)
                    
                    AreaMark(
                        x: .value("Period", index),
                        y: .value("Rate", rate)
                    )
                    .foregroundStyle(selectedType.color.opacity(0.1).gradient)
                }
            }
            .frame(height: 200)
            .chartYScale(domain: 0...1)
            .chartYAxis {
                AxisMarks(values: [0, 0.25, 0.5, 0.75, 1]) { value in
                    AxisGridLine()
                    AxisValueLabel {
                        Text("\(Int(value.as(Double.self)! * 100))%")
                    }
                }
            }
            .chartXAxis {
                AxisMarks(values: .automatic(desiredCount: selectedTimeRange == .month ? 4 : 12)) { value in
                    AxisGridLine()
                    AxisValueLabel {
                        if let intValue = value.as(Int.self) {
                            Text(selectedTimeRange == .month ? "第\(intValue + 1)周" : "\(intValue + 1)月")
                        }
                    }
                }
            }
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(15)
    }
    
    private var barChartView: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("修炼时长分布")
                .font(.headline)
            
            Chart {
                ForEach(cultivationData.durationDistribution[selectedType] ?? [], id: \.duration) { item in
                    BarMark(
                        x: .value("Duration", item.duration),
                        y: .value("Count", item.count)
                    )
                    .foregroundStyle(selectedType.color.gradient)
                }
            }
            .frame(height: 200)
            .chartXAxis {
                AxisMarks(values: .automatic(desiredCount: 5)) { value in
                    AxisGridLine()
                    AxisValueLabel {
                        if let intValue = value.as(Int.self) {
                            Text("\(intValue)分钟")
                        }
                    }
                }
            }
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(15)
    }
    
    private var radarChartView: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("修炼能力雷达图")
                .font(.headline)
        
        RadarChartView(
            data: cultivationData.radarChartData[selectedType] ?? [],
            labels: cultivationData.radarChartLabels,
            color: selectedType.color
        )
        .frame(height: 250)
    }
    .padding()
    .background(Color(.systemBackground))
    .cornerRadius(15)
}
    
    private var scatterPlotView: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("修炼时长与效果关系")
                .font(.headline)
            
            Chart {
                ForEach(cultivationData.scatterPlotData[selectedType] ?? [], id: \.self) { item in
                    PointMark(
                        x: .value("Duration", item.duration),
                        y: .value("Effect", item.effect)
                    )
                    .foregroundStyle(selectedType.color)
                }
            }
            .frame(height: 200)
            .chartXAxis {
                AxisMarks(values: .automatic(desiredCount: 5)) { value in
                    AxisGridLine()
                    AxisValueLabel {
                        if let intValue = value.as(Int.self) {
                            Text("\(intValue)分钟")
                        }
                    }
                }
            }
            .chartYAxis {
                AxisMarks(values: .automatic(desiredCount: 5)) { value in
                    AxisGridLine()
                    AxisValueLabel {
                        if let intValue = value.as(Int.self) {
                            Text("\(intValue)%")
                        }
                    }
                }
            }
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(15)
    }
    
    private var gaugeChartView: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("修炼进度")
                .font(.headline)
            
            Gauge(value: cultivationData.progressGauge[selectedType] ?? 0, in: 0...1) {
                Text(selectedType.rawValue)
            } currentValueLabel: {
                Text("\(Int((cultivationData.progressGauge[selectedType] ?? 0) * 100))%")
            }
            .gaugeStyle(.accessoryCircular)
            .tint(selectedType.color)
            .scaleEffect(2)
            .frame(height: 100)
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(15)
    }
}

enum TimeRange: String, CaseIterable {
    case month = "月"
    case year = "年"
}

enum TaskType: String, CaseIterable {
    case technique = "炼技"
    case body = "炼体"
    case mind = "炼神"
    
    var color: Color {
        switch self {
        case .technique: return .blue
        case .body: return .green
        case .mind: return .purple
        }
    }
}

struct EnhancedCultivationData {
    var heatmapData: [TimeRange: [[Double]]]
    var completionRates: [TaskType: [TimeRange: [Double]]]
    var durationDistribution: [TaskType: [DurationItem]]
    var radarChartData: [TaskType: [Double]]
    var radarChartLabels: [String]
    var scatterPlotData: [TaskType: [ScatterItem]]
    var progressGauge: [TaskType: Double]
}

struct DurationItem: Identifiable {
    let id = UUID()
    let duration: Int
    let count: Int
}

struct ScatterItem: Identifiable, Hashable {
    let id = UUID()
    let duration: Int
    let effect: Double
}

struct EnhancedCultivationStatisticsView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView {
            EnhancedCultivationStatisticsView(cultivationData: EnhancedCultivationData(
                heatmapData: [
                    .month: (0..<5).map { _ in (0..<7).map { _ in Double.random(in: 0...1) } },
                    .year: (0..<52).map { _ in (0..<7).map { _ in Double.random(in: 0...1) } }
                ],
                completionRates: [
                    .technique: [
                        .month: (0..<4).map { _ in Double.random(in: 0.5...1) },
                        .year: (0..<12).map { _ in Double.random(in: 0.5...1) }
                    ],
                    .body: [
                        .month: (0..<4).map { _ in Double.random(in: 0.5...1) },
                        .year: (0..<12).map { _ in Double.random(in: 0.5...1) }
                    ],
                    .mind: [
                        .month: (0..<4).map { _ in Double.random(in: 0.5...1) },
                        .year: (0..<12).map { _ in Double.random(in: 0.5...1) }
                    ]
                ],
                durationDistribution: [
                    .technique: (0..<5).map { DurationItem(duration: $0 * 15, count: Int.random(in: 10...50)) },
                    .body: (0..<5).map { DurationItem(duration: $0 * 15, count: Int.random(in: 10...50)) },
                    .mind: (0..<5).map { DurationItem(duration: $0 * 15, count: Int.random(in: 10...50)) }
                ],
                radarChartData: [
                    .technique: (0..<5).map { _ in Double.random(in: 0.3...0.9) },
                    .body: (0..<5).map { _ in Double.random(in: 0.3...0.9) },
                    .mind: (0..<5).map { _ in Double.random(in: 0.3...0.9) }
                ],
                radarChartLabels: ["专注度", "持续性", "效率", "创新", "适应性"],
                scatterPlotData: [
                    .technique: (0..<20).map { _ in ScatterItem(duration: Int.random(in: 15...120), effect: Double.random(in: 0.3...0.9)) },
                    .body: (0..<20).map { _ in ScatterItem(duration: Int.random(in: 15...120), effect: Double.random(in: 0.3...0.9)) },
                    .mind: (0..<20).map { _ in ScatterItem(duration: Int.random(in: 15...120), effect: Double.random(in: 0.3...0.9)) }
                ],
                progressGauge: [
                    .technique: Double.random(in: 0.3...0.9),
                    .body: Double.random(in: 0.3...0.9),
                    .mind: Double.random(in: 0.3...0.9)
                ]
            ))
        }
    }
}

